from flask import Blueprint, request, jsonify, render_template
from app.models.db import get_db
from app.utils.doc_utils import generate_transfer_id, generate_doc_id
from datetime import datetime
from flask_login import login_required
transfer_bp = Blueprint('transfer', __name__)

# 转移记录页面
@transfer_bp.route('/transfer/records')
def transfer_records_page():
    return render_template('transfer_records.html')

# 虚拟库存转自有库存（带/api前缀）
@transfer_bp.route('/api/transfer/virtual-to-own', methods=['POST'])
@login_required
def virtual_to_own_transfer():
    data = request.get_json()
    required = ['supplier_id', 'product_id', 'quantity', 'warehouse']
    if not all(k in data for k in required):
        return jsonify({'status': 'error', 'message': '缺少参数（供应商ID、商品ID、数量、仓库）'}), 400
    try:
        quantity = int(data['quantity'])
        if quantity <= 0:
            return jsonify({'status': 'error', 'message': '数量必须为正数'}), 400
    except ValueError:
        return jsonify({'status': 'error', 'message': '数量必须是数字'}), 400

    transfer_id = generate_transfer_id()
    create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    db = get_db()
    cursor = db.cursor()

    try:
        cursor.execute("""
        SELECT si.*, s.supplier_name FROM supplier_inventory si
        JOIN supplier s ON si.supplier_id = s.id
        WHERE si.supplier_id=? AND si.product_id=?
        """, (data['supplier_id'], data['product_id']))
        virtual_item = cursor.fetchone()
        if not virtual_item:
            return jsonify({'status': 'error', 'message': '虚拟库存不存在'}), 404
        if virtual_item['virtual_quantity'] < quantity:
            return jsonify({'status': 'error', 'message': f'虚拟库存不足（当前：{virtual_item["virtual_quantity"]}）'}), 400

        # 扣减虚拟库存
        cursor.execute("""
        UPDATE supplier_inventory SET virtual_quantity=virtual_quantity-?, update_time=?
        WHERE id=?
        """, (quantity, create_time, virtual_item['id']))

        # 增加自有库存并生成入库单据
        product_name = virtual_item['product_name']
        doc_id = generate_doc_id("入库")
        cursor.execute('''INSERT INTO stock_doc (doc_id, doc_type, warehouse, operator, create_time)
                          VALUES (?, ?, ?, ?, ?)''', (doc_id, "入库", data['warehouse'], "admin", create_time))
        cursor.execute('''INSERT INTO stock_doc_item (doc_id, product_id, product_name, quantity)
                          VALUES (?, ?, ?, ?)''', (doc_id, data['product_id'], product_name, quantity))
        cursor.execute("SELECT * FROM inventory WHERE product_id=? AND warehouse=?", 
                      (data['product_id'], data['warehouse']))
        if cursor.fetchone():
            cursor.execute("UPDATE inventory SET quantity=quantity+?, update_time=? WHERE product_id=? AND warehouse=?",
                          (quantity, create_time, data['product_id'], data['warehouse']))
        else:
            cursor.execute("INSERT INTO inventory VALUES (NULL, ?, ?, ?, ?, ?)",
                          (product_name, data['product_id'], quantity, data['warehouse'], create_time))

        # 记录转移记录
        cursor.execute('''
        INSERT INTO zero_stock_transfer (
            transfer_id, supplier_id, supplier_name, product_id, product_name,
            quantity, direction, create_time, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ''', (
            transfer_id, data['supplier_id'], virtual_item['supplier_name'],
            data['product_id'], product_name, quantity, "VIRTUAL_TO_OWN",
            create_time, "已完成"
        ))

        db.commit()
        return jsonify({
            'status': 'success',
            'message': '虚拟库存转移成功',
            'transfer_id': transfer_id,
            'doc_id': doc_id
        })
    except Exception as e:
        db.rollback()
        return jsonify({'status': 'error', 'message': f'转移失败：{str(e)}'}), 500

# 获取转移记录列表（带/api前缀）
@transfer_bp.route('/api/transfer/records', methods=['GET'])
@login_required
def get_transfer_records():
    supplier_id = request.args.get('supplier_id', '')
    product_id = request.args.get('product_id', '')
    cursor = get_db().cursor()
    query = "SELECT * FROM zero_stock_transfer WHERE 1=1"
    params = []
    if supplier_id:
        query += " AND supplier_id=?"
        params.append(supplier_id)
    if product_id:
        query += " AND product_id=?"
        params.append(product_id)
    query += " ORDER BY create_time DESC"
    cursor.execute(query, params)
    return jsonify([dict(row) for row in cursor.fetchall()])